//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
var disabled = true;
var gloData = app.globalData;
var codeString = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uid: "",
    orderMoney: "",
    remark: "",
    // discountId:"",
    // isCanUseLiquidationDiscountCard:"",
    isDelayedFinishOrder: "",
    // businessData: {},
    // 余额，微信
    payType: "",
    payFlag: true,
    // 分期
    firstMoney: "",
    isCanInstalments: "",
    isInstalments: "0",
    instalmentsNum: "",
    instalmentsNumArr: ['3个月', '4个月', '5个月', '6个月', '7个月', '8个月', '9个月', '10个月', '11个月', '12个月'],
    // 生成订单信息
    orderData: "",
    // 输入支付密码
    //是否展示密码输入层
    showPayPwdInput: false,
    // 订单号  
    orderNumber: "",
    //输入的密码
    payPasswords: "",
    //文本框焦点
    payFocus: true,
    // 是否已经设置支付密码
    isAlreadyPayPassword: "",
    // 商家信息
    businessId: 0,
    instalmentsNumm: 0,
    BusinessAllName: "",
    BusinessHeaderImage: "",
    // 授权
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    powerFlag: true,
    phoneFlag: true,
    code: 'authMSG',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType'),
      // payFlag:wx.getStorageSync('payFlag'),
      isAlreadyPayPassword: wx.getStorageSync('isAlreadyPasswords'),
      businessId: options.businessId,
    })
    this.GetUserInfoByIDs();
    this.GetBusinessShopInfo();
    // this.GetGoodInfoByID();
    // console.log(payFlag);
    // console.log(options.businessId);
    // 登录
    var that = this;
    wx.login({
      success(res) {
        //js调用登陆命令获取到code
        if (res.code) {
          codeString = res.code
          //通过code调用自己服务接口获取到openid
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  // 获取商家信息
  GetBusinessShopInfo: function () {
    var that = this;
    var businessId = this.data.businessId;
    var BusinessAllName = this.data.BusinessAllName;
    var BusinessHeaderImage = this.data.BusinessHeaderImage;
    wx.request({
      url: baseJs.api_User + "GetBusinessShopInfo/" + businessId,
      success: function (res) {
        // console.log(baseJs.api_User + "GetBusinessShopInfo/" + businessId);
        var json = res.data;
        that.setData({
          // businessId: json.ResultData.businessId,
          BusinessAllName: json.ResultData.BusinessAllName,
          BusinessHeaderImage: json.ResultData.BusinessHeaderImage,
        })
        // wx.setNavigationBarTitle({
        //   title: json.ResultData.BusinessAllName,
        // })
        console.log(json);

      }
    })
  },
  //获取用户信息
  GetUserInfoByIDs: function () {
    var that = this;
    var uid = this.data.uid;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetUserInfoByIDs&UID=" + uid),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        var json = JSON.parse(baseJs.decryUrl(res.data));
        that.setData({
          isCanInstalments: json.ResultData.IsCanInstalments,
        })
      }
    })
  },
  //分期选择
  instalmentsTap: function (e) {
    // console.log(e);
    if (e.detail.value.length == 0) {
      this.setData({
        isInstalments: "0",
        instalmentsNum: "",
        firstMoney: "",
      })
    } else {
      this.setData({
        isInstalments: e.detail.value[0]
      })
    }
  },

  // 到账额度
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value);
    var instalmentsNumArr = this.data.instalmentsNumArr;
    var instalmentsNum = this.data.instalmentsNum;
    instalmentsNum = instalmentsNumArr[e.detail.value];
    this.setData({
      instalmentsNum: instalmentsNum,
    })
  },
  // 支付弹出显示
  payShow: function () {
    this.setData({
      payFlag: !this.data.payFlag,
    })
  },

  // 交易金额
  orderMoney: function (e) {
    // console.log(e);
    this.setData({
      orderMoney: e.detail.value
    })
  },
  // 备注信息
  remark: function (e) {
    console.log(e);
    this.setData({
      remark: e.detail.value
    })
  },
  firstMoney: function (e) {
    this.setData({
      firstMoney: e.detail.value
    })
  },
  instalmentsNum: function (e) {
    this.setData({
      instalmentsNum: e.detail.value
    })
  },

  //显示支付密码输入层
  showInputLayer: function () {
    this.setData({
      showPayPwdInput: true,
      payFocus: true,
    });
  },
  //隐藏支付密码输入层
  cancelInputPasswords: function () {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: '',
    });
  },
  // 获取焦点
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function (e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },
  // 授权登录
  bindAuthoriza: function () {
    var that = this;
    this.setData({
      powerFlag: false
    })
  },
  //获取授权用户的信息
  bindGetUserInfo(e) {
    wx.getSetting({
      success: res => {
        //如果经过授权
        if (res.authSetting['scope.userInfo']) {
          this.setData({
            hideBtn: true
          })
          //获取用户openid
          wx.getUserInfo({
            success: res => {
              var that = this;
              var uid = this.data.uid;
              var resultData = this.data.resultData;
              this.data.userInfo = res.userInfo,
                this.data.userInfo.code = gloData.code,
                wx.request({
                  url: baseJs.api + baseJs.encryUrl("method=GetSmallProgramOpenIdFromUserCode&Code=" + codeString + "&UID=" + this.data.uid),
                  success: function (res) {
                    console.log(res);
                    resultData = JSON.parse(baseJs.decryUrl(res.data));
                    console.log(resultData);
                    that.setData({
                      userInfo: app.globalData.userInfo,
                      // uid: app.globalData.userInfo.uid,
                    })

                  }

                })

            }
          })
        }
      }
    })
  },
  // 授权登录
  powerTap: function () {
    this.setData({
      powerFlag: !this.data.powerFlag,
    })
    wx.showToast({
      title: '授权成功',
      icon: 'none',
      duration: 2000
    });
  },

  getUserInfo: function (e) {
    var that = this;
    var uid = this.data.uid;
    // console.log(e);
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      hasUserInfo: true,
    })

  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
  },
  // 确认付款
  surePay: function () {
    var that = this;
    var uid = this.data.uid;
    var businessId = this.data.businessId;
    var orderMoney = this.data.orderMoney;
    var remark = this.data.remark;
    var firstMoney = this.data.firstMoney;
    var instalmentsNumm = this.data.instalmentsNumm;
    var isInstalments = this.data.isInstalments;
    var instalmentsNum = this.data.instalmentsNum;
    var payFlag = this.data.payFlag;
    wx.showLoading({
      title: '加载中',
    })
    // console.log("method=payFreePay1&UID=" + uid + "&Bid=" + businessId + "&OrderMoney=" + orderMoney + "&Remark=" + remark + "&IsCanInstalments=" + isInstalments + "&FirstEnterMa=" + firstMoney + "&PeriodsNumber=" + instalmentsNumm);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=payFreePay1&UID=" + uid + "&Bid=" + businessId + "&OrderMoney=" + orderMoney + "&Remark=" + remark + "&IsCanInstalments=" + isInstalments + "&FirstEnterMa=" + firstMoney + "&PeriodsNumber=" + instalmentsNumm),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        if (json.ResultFlag == 1) {
          console.log(json);
          var orderData = json.ResultData;
          that.setData({
            payFlag: false,
            orderData: orderData,
          })
          console.log(orderData);
          wx.hideLoading();
        } else {
          setTimeout(function () {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }, 200)
          wx.hideLoading();
        }

      }
    })
  },
  //余额或微信 
  radioChange: function (e) {
    this.setData({
      payType: e.detail.value,
    });
  },
  //去支付
  goPay: function () {
    var that = this;
    var payType = this.data.payType;
    var orderData = this.data.orderData;
    var orderNumber = orderData.ordernumber;
    var isAlreadyPayPassword = this.data.isAlreadyPayPassword;
    var uid = this.data.uid;
    if (payType == '') {
      wx.showToast({
        title: "请选择支付方式！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({
      payFlag: true,
    })
    if (payType == "1") {
      if (isAlreadyPayPassword == '1') {
        that.setData({
          showPayPwdInput: true,
          payFocus: true
        })
      } else {
        wx.showToast({
          title: "请先去设置支付密码！",
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      wx.showLoading({
        title: '加载中',
      })
      // console.log("method=FreePaySmallProgramWeiXinPayRequest&OrderNumber=" + orderNumber + "&UID=" + uid);
      wx.request({
        // 微信支付
        url: baseJs.api + baseJs.encryUrl("method=FreePaySmallProgramWeiXinPayRequest&OrderNumber=" + orderNumber + "&UID=" + uid),
        success: function (res) {
          var json = JSON.parse(baseJs.decryUrl(res.data));
          console.log(json);
          wx.hideLoading();
          if (json.ResultFlag == 1) {
            wx.requestPayment({
              timeStamp: json.ResultData.timeStamp,
              nonceStr: json.ResultData.nonceStr,
              package: json.ResultData.package,
              signType: json.ResultData.signType,
              paySign: json.ResultData.paySign,
              success(res) {
                console.log(res);
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 2000
                });
              },
              fail(res) {
                console.log(res);
                wx.showToast({
                  title: res.err_desc,
                  icon: 'none',
                  duration: 2000
                });
              }
            })
          } else {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }
        }
      })
    }
  },
  //输入密码--确定 （余额支付）
  surePasswords: function () {
    var that = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var orderData = this.data.orderData;
    var orderNumber = orderData.ordernumber;
    wx.request({
      // 支付密码是否正确
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {
          wx.showLoading({
            title: '加载中',
          })
          wx.request({
            // 余额支付
            url: baseJs.api + baseJs.encryUrl("method=FreePayYuePayRequest&OrderNumber=" + orderNumber),
            success: function (res) {
              var json = JSON.parse(baseJs.decryUrl(res.data))
              console.log(json);
              if (json.ResultFlag == 1) {
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1000)
              } else {
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
              wx.hideLoading();
            }
          })
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },


})